<?php

namespace app\store\controller;
use think\Request;
use think\Validate;
use think\Db;
use think\Cache;
class Games extends ApiCommon
{
	//添加中奖纪录
	public function addGameReward(){
		$userid = input('userid/d',0);
        $gameid = input('gameid/d',0);
		
		if($userid<=0 || $gameid<=0){
			$this->returnMsg('-1','信息错误');
		}
		
		$userinfo = Db::name('userinfo')->where(['userid'=>$userid])->find();
		if(empty($userinfo)){
			$this->returnMsg('-1','用户信息错误');
		}
		
		$game_reward = Db::name('game_reward')->where(['userid'=>$userid,'gameid'=>$gameid])->find();
		$gameinfo = Db::name("info_game")->where(['gameid'=>$gameid])->find();
		$addtime = time();
		if(empty($game_reward) && !empty($gameinfo)){
			
			$goodsid = $gameinfo['goodsid'];
			$goodsinfo = Db::name('goods')->where(['id'=>$goodsid])->field('id,storeid')->find();
			if(empty($goodsinfo)){
				$this->returnMsg('ok','商品信息为空');
			}
			
			if($goodsinfo['storeid']!=$userinfo['storeid']){
				$this->returnMsg('-1','店铺信息错误');
			}
			
			Db::query("insert into ml_game_reward(userid,gameid,addtime,state,goodsid)values($userid,$gameid,$addtime,1,$goodsid)");
			$this->returnMsg('ok','添加奖励成功');
		}
		
		$this->returnMsg('0','已经添加过奖励');
	}
	
	//显示游戏奖励
	public function showGameReward(){
		$userid = input('userid/d',0);
		
		$infos = Db::query("select ml_game_reward.*,ml_game_reward.id as awardid,ml_goods.id,gname,icon,message from ml_game_reward,ml_goods 
		where ml_goods.id = goodsid and userid = $userid and ml_game_reward.state = 1");		
		
//		$goodsStr = ConnResultStr($infos);	
//		$connRes = Db::name("consumelist")->whereIn('goodsid',$goodsStr)->select();
		
		$this->returnMsg('ok','',$infos);
	}
	
	//获取游戏奖励
	public function getGameReward(){
		$userid = input('userid/d',0);
		$grewardid = input('grewardid','');
		
		$grewardidstr = rtrim($grewardid,",");
		if(strlen($grewardidstr)<=0){
			$this->returnMsg('-1','参数错误！');
		}
		
		$res = Db::name('game_reward')
		->where(['userid'=>$userid,'state'=>1])
		->whereIn('id',$grewardidstr)
		->select();
		$userinfo = Db::name('userinfo')->where(['userid'=>$userid])->find();
		
		if(empty($userinfo)){
			$this->returnMsg('-1','用户信息错误！');
		}
		
		$phone = isBindPhone($userid);
		if($phone == "" || $phone == null){
			$this->returnMsg('-2','请先绑定手机！');
		}
		
		if(empty($res)){
			$this->returnMsg('-3','你还没有可以领取的奖励！');
		}
		
		foreach($res as $k=>$v){
			Db::name('game_reward')->where(['id'=>$v['id']])->save(['state'=>2]);
			//开始添加奖品
			$addres = AddGoodsToUser($v['goodsid'],$userid,$userinfo['storeid']);
		}
		
		$this->returnMsg($addres['state'],$addres['msg']);
	}
}	
?>